package com.yuncheng.spcyApi.webOffice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuncheng.spcyApi.config.SpcyMinioUtils;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.webOffice.WebOfficeConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.common.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;
import utils.Util;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Component
public class WebOfficeFile {
    private static final Logger log = LoggerFactory.getLogger(WebOfficeFile.class);

    @Resource
    private BusinessConstant businessConstant;

    @Resource
    private SpcyMinioUtils spcyMinioUtils;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private ISpcyZltxwjFlowService spcyZltxwjFlowService;

    @Resource
    @Lazy
    private ISpcyRsWjmbService spcyRsWjmbService;

    @Resource
    private WebOfficeConstant webOfficeConstant;

    /**
     * 上传文件到WebOffice服务器（申请事项）
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFile(SpcySqsxWjjl wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        InputStream minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(saveUrl));
        if (minioInput == null){
            return Result.error("文件流不存在！");
        }
        File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }


    /**
     * 上传文件到WebOffice服务器（申请事项）
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByOnlyRead(SpcySqsxWjjl wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        InputStream minioInput = null;
        minioInput = spcyMinioUtils.getObject(localFileUploadUtils.getSqsxWjjlRelativeUrl(saveUrl));
        if (minioInput == null){
            return Result.error("文件流不存在！");
        }

        File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器(通用文件)
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeCommonFileByOnlyRead(SpcySqsxWjjl wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        InputStream minioInput = null;
        minioInput = spcyMinioUtils.getObject(saveUrl);
        if (minioInput == null){
            return Result.error("文件流不存在！");
        }
        File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));

        /*File file = new File(localFileUploadUtils.getSqsxWjjlAbsUrl(saveUrl));
        if (!file.exists()){
            return Result.error("本地文件不存在");
        }*/

        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器(通用文件)
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeQyFileByOnlyRead(SpcySqsxQywjcl wjjl, String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }

        InputStream minioInput = null;
        minioInput = spcyMinioUtils.getObject(saveUrl);
        if (minioInput == null){
            return Result.error("文件流不存在！");
        }
        File file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));

        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器  (质量体系文件-流程)
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByZltxwj(SpcyZltxwjFlow wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        File file = null;
        if (businessConstant.isEnableZltxwnjMinio){
            InputStream minioInput = spcyMinioUtils.getObject(saveUrl);;
            if (minioInput == null){
                return Result.error("文件流不存在！");
            }
            file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));
        }else {
            file = new File(businessConstant.UPLOAD_FILE_ROOT + saveUrl);
            if (!file.exists()){
                return Result.error("本地文件不存在");
            }
        }

        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器  (质量体系文件) 资源库
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileBaseByZltxwj(SpcyZltxwjBasic wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        /*File file = new File(businessConstant.UPLOAD_FILE_ROOT + saveUrl);
        if (!file.exists()){
            return Result.error("本地文件不存在");
        }*/

        File file = null;
        if (businessConstant.isEnableZltxwnjMinio){
            InputStream minioInput = spcyMinioUtils.getObject(saveUrl);
            if (minioInput == null){
                return Result.error("文件流不存在！");
            }
            file = localFileUploadUtils.asFile(minioInput, Util.getWjHz(fileName));
        }else {
            file = new File(businessConstant.UPLOAD_FILE_ROOT + saveUrl);
            if (!file.exists()){
                return Result.error("本地文件不存在");
            }
        }

        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = saveUrl.replaceAll("\\\\","/");
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器 （文件模板库）
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByWjmb(SpcyRsWjmb wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        File file = null;
        if (localFileUploadUtils.isEnableMinioWjmbFile()){
            file = localFileUploadUtils.convertMinioToFile(localFileUploadUtils.getWjmbRelativeUrl(saveUrl), wjjl.getFwjlx());

        }else {

            file = new File(localFileUploadUtils.getWjmbAbsUrl(saveUrl));
            if (!file.exists()) {
                return Result.error("本地文件不存在");
            }
        }

//        fileName = "xxx.doc";
        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        fileName = CharacterEncodingConvertUtils.replaceSpecialString(fileName);
//        System.out.println("2Name: "+fileName);
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);
//        System.out.println("2: "+saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
//            multipartEntityBuilder.setMode(HttpMultipartMode.STRICT);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器  (档案文件)
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByDa(SpcyDaWjjl wjjl,String fileName, String saveUrl){
        if (StringUtils.isBlank(saveUrl)){
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")){
            return Result.error("pdf文件无法上传");
        }

        /*
        // 本地文件流
        File file = new File(businessConstant.UPLOAD_FILE_ROOT + saveUrl);
        if (!file.exists()){
            return Result.error("本地文件不存在");
        }

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}",e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        */

        /*fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);*/



        // minio文件流
        InputStream fileInputStream = spcyMinioUtils.getObject(saveUrl);

        if (StringUtils.isEmpty(fileName)){
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        }catch (Exception e){
            log.error("上传WebOffice文件失败：{}",e.getMessage());
            return Result.error("上传WebOffice文件失败: "+e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 将WebOffice服务器的文件，转为Pdf，生成pdf文件地址并下载
      * @param wjjl 文件id
     * @param saveUrl WebOffice服务器保存的文件路径
     * @return
     */
    public Result getDocxToPdfFile(SpcySqsxWjjl wjjl,String saveUrl){
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            Result result = this.uploadWebOfficeFile(wjjl,wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                return Result.error(result.getMessage());
            }
        }

        String resultMsg = "";
        // 创建HttpGet对象
        StringBuffer urlString = new StringBuffer(webOfficeConstant.Dcs_Docx_To_Pdf_Api);


        StringBuffer fileUrl = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        fileUrl.append("?").append("filePath").append("=").append(saveUrl);
//        fileUrl.append("&").append("isDeleteFile").append("=").append("false");

        NameValuePair pair1 = new BasicNameValuePair("convertType", "3");
        NameValuePair pair2 = new BasicNameValuePair("fileUrl",fileUrl.toString());
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(pair1);
        pairList.add(pair2);

        HttpPost httpRequest = new HttpPost(urlString.toString());

        httpRequest.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");

        httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");

        // json参数
        try {
            httpRequest.setEntity(new UrlEncodedFormEntity(pairList,"UTF-8"));

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            log.info("response-statusCode: {}", response.getStatusLine().getStatusCode());

            /*String locationUrl = response.getFirstHeader("location").getValue();
            log.info("HttpClient locationUrl  => "+locationUrl);
            log.info("4--HttpClient StatusCode  => "+response.getStatusLine().getStatusCode());*/

            /*if (response.getStatusLine().getStatusCode() == 302) {
                *//*Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD上
                String newuri = header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请
                log.info("newuri: {}", newuri);

                httpRequest = new HttpPost("https://bg.yjj.gxzf.gov.cn"+newuri);
                httpRequest.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");
                httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

                response = HttpClients.createDefault().execute(httpRequest);
                int code = response.getStatusLine().getStatusCode();
                locationUrl = response.getLastHeader("location").getValue();
                log.info("5--HttpClient new Code  => "+code);
                log.info("6--HttpClient locationUrl  => "+locationUrl);*//*
            }*/


            if (response.getStatusLine().getStatusCode() == 200){

                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject2 = JSONObject.parseObject(s);
                    log.info("WebOffice将Docx转换为Pdf,返回值: {}",jsonObject2);

                    String errorcode = jsonObject2.getString("errorcode");
                    if (Integer.valueOf(errorcode) == 0){
                        JSONObject data = jsonObject2.getJSONObject("data");
                        String viewUrl = data.getString("viewUrl"); // pdf文件路径
                        log.info("viewUrl: {}",viewUrl);

                        if (StringUtils.isBlank(viewUrl)) {
                            return Result.error("下载pdf文件路径viewUrl参数为空");
                        }

                        this.getDownloadPdfFile2(wjjl, viewUrl); // 下载pdf文件

                        log.info("WebOffice将word转pdf的errorcode: {}",errorcode);
                    }else {
                        resultMsg = jsonObject2.getString("message");
                        log.error("WebOffice将word转pdf的message: {}",resultMsg);
                        return Result.error("WebOffice将word转pdf的message: "+resultMsg);
                    }
                }
            }else {
                return Result.error("WebOffice将word转pdf的Code: "+response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("WebOffice将word转pdf的Exception: {}",e.getMessage());
            return Result.error("WebOffice将word转pdf的Exception: "+e.getMessage());
        }

        return Result.ok("转换成功");
    }

    /**
     * 将WebOffice服务器word文档转为Pdf的文件下载（申请事项文件）
     * @param wjjl 当前文件对象
     * @param viewUrl pdf文件下载https路径
     */
    public void getDownloadPdfFile2(SpcySqsxWjjl wjjl, String viewUrl){
       /* StrBuilder url = new StrBuilder(WebOfficeFIle.WebOffice_download_Api);
        url.append("?").append("filePath").append(saveUrl);
        url.append("&").append("isDeleteFile").append(isDel);*/

        try{
            HttpGet httpget = new HttpGet(viewUrl);
            httpget.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",viewUrl);
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);
            HttpEntity entity=response.getEntity();
            InputStream is=entity.getContent();

            String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());

            String realurl = localFileUploadUtils.getTempFileRootUrl() + ml;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()){
                newDirUrl.mkdirs();
            }

            String pdfname = GetUuIdUtils.NotReplaceUuId() + ".pdf"; // 文件名称
            String outFileUrl = realurl + "/" + pdfname;

            FileOutputStream fileout = new FileOutputStream(outFileUrl);
            byte[]buffer = new byte[1024*10];
            int ch = 0;
            while((ch = is.read(buffer)) != -1){
                fileout.write(buffer,0,ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            boolean flag = false;
            // minio上传
            if (localFileUploadUtils.isEnableMinioWjjlFile()){
                String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(ml+"/"+pdfname);
                flag = spcyMinioUtils.putFlagFile(objectName,new File(outFileUrl),".pdf");
            }else {
                flag = true;
            }

            if (flag){
                String fcflj = wjjl.getFcflj(); // 旧的文档路径
                if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
                }

                wjjl = spcySqsxWjjlService.genWjjlByScpdf(wjjl, ml + "/" + pdfname, fcflj, pdfname);
                spcySqsxWjjlService.updateById(wjjl);
            }

        }catch(Exception e){
            log.error("将WebOffice服务器word文档转为Pdf的文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
    public void getWebOfficeDownloadFile2(SpcySqsxWjjl wjjl, String saveUrl, boolean isDel){
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                return;
            }*/
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(isDel);


        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();


            String ml = "/" + DateConversionUtils.DateToMonthTwo(new Date());

            String realurl = localFileUploadUtils.getTempFileRootUrl() +ml;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            String pdfname = GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(saveUrl); // 文件名称

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            boolean flag = false;
            if (localFileUploadUtils.isEnableMinioWjjlFile()){
                String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(ml+"/"+pdfname);
                flag = spcyMinioUtils.putFlagFile(objectName, new File(realurl + "/" + pdfname), Util.getWjHz(saveUrl));
            }else {
                flag = true;
            }

            if (flag){
                String fcflj = wjjl.getFcflj(); // 旧的文件

                wjjl.setFcflj(ml + "/" + pdfname);
                if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                    localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
                }

                wjjl.setFjdcflj(fcflj);
                wjjl.setFwjccmc(pdfname);
                spcySqsxWjjlService.updateById(wjjl);

                this.deleteFile(fcflj);
            }

            /*String fcflj = wjjl.getFcflj(); // 旧的文件
            wjjl.setFcflj(ml + "/" + pdfname);
            if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                localFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
            }
            wjjl.setFjdcflj(fcflj);
            wjjl.setFwjccmc(pdfname);
            boolean isFlag = spcySqsxWjjlService.updateById(wjjl);
            if (isFlag){

                if (localFileUploadUtils.isEnableMinioWjjlFile()){
                    String objectName = localFileUploadUtils.getSqsxWjjlRelativeUrl(ml+"/"+pdfname);
                    spcyMinioUtils.putFile(objectName,new File(realurl + "/" + pdfname),Util.getWjHz(saveUrl));
                }

                this.deleteFile(fcflj);
            }*/

        }catch(Exception e){
            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载  （质量体系文件）
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
    public void getWebOfficeDownloadFile2ByZltxwj(SpcyZltxwjFlow wjjl, String saveUrl, boolean isDel){
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                return;
            }*/
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(isDel);

        String pdfname = GetUuIdUtils.ReplaceUuId() + Util.getWjHz(saveUrl); // 文件名称
        boolean flag = true;
        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            // 目录
            String ml = "/" + SpcyConstant.Flow_Zltxwj_File_Base_Url + "/" + DateConversionUtils.DateToMonthTwo(new Date());

            String newCflj = ml + "/" + pdfname; // 新存放路径
            String realurl = ""; // pdf保存路径

            if (businessConstant.isEnableZltxwnjMinio) {
                realurl = localFileUploadUtils.getTempFileRootUrl();
            }else {
                realurl = businessConstant.UPLOAD_FILE_ROOT + ml;
            }

            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            if (businessConstant.isEnableZltxwnjMinio){
                flag = spcyMinioUtils.putFlagFile(newCflj, new File(realurl + "/" + pdfname), Util.getWjHz(pdfname));
            }

            if (flag) {
                String fcflj = wjjl.getFwjlj(); // 旧的文件
                wjjl.setFwjlj(newCflj);
                if (StringUtils.isNotBlank(wjjl.getFjdwjlj())) {
                    localFileUploadUtils.deleteLocalFileUrlByZltxwj(wjjl.getFjdwjlj());
                }
                wjjl.setFjdwjlj(fcflj);
                boolean isFlag = spcyZltxwjFlowService.updateById(wjjl);
                if (isFlag) {
                    this.deleteFile(fcflj);
                }
            }

        }catch(Exception e){
            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
        }

        if (!flag){
            throw new BusinessException("保存文件失败！");
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载  （文件模板库）
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
    public void getWebOfficeDownloadFile2ByWjmb(SpcyRsWjmb wjjl, String saveUrl, boolean isDel){
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                return;
            }*/
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(isDel);

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String sjmc = "";
            if (StringUtils.isNotBlank(wjjl.getFsqsxid())){
                sjmc = wjjl.getFsqsxid() + "-" + GetUuIdUtils.ReplaceUuId();
            }else {
                if (StringUtils.isNotBlank(wjjl.getFmbbt())) {
                    sjmc = wjjl.getFmbbt() + GetUuIdUtils.ReplaceUuId();
                } else {
                    sjmc = GetUuIdUtils.ReplaceUuId();
                }
            }
            String pdfname = sjmc + Util.getWjHz(saveUrl); // 文件名称

            String ml = "";
            if (StringUtils.isBlank(wjjl.getFsqsxid())) {
                if (StringUtils.isNotBlank(wjjl.getFywflcode())) {
                    ml = "/" + wjjl.getFywflcode();
                } else {
                    ml = "/" + DateConversionUtils.DateToMonth(new Date());
                }
            }else {
                ml = "/sqsx" + DateConversionUtils.DateToMonthTwo(new Date());
            }

            String realurl = "";
            if (localFileUploadUtils.isEnableMinioWjmbFile()){
                realurl = localFileUploadUtils.getTempFileRootUrl();
            }else {
                realurl = localFileUploadUtils.getWjmbAbsUrl(ml);
            }

            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            String fcflj = wjjl.getFcflj(); // 旧的文件
            wjjl.setFcflj(ml + "/" + pdfname);
            wjjl.setFwjccmc(pdfname);

            boolean isUploadFlag = true;
            if (businessConstant.isEnableWjmbMinio){
                String objectName = localFileUploadUtils.getWjmbRelativeUrl(ml + "/" + pdfname);
                isUploadFlag = spcyMinioUtils.putFlagFile(objectName, new File(realurl + "/" + pdfname), Util.getWjHz(saveUrl));
            }

            if (isUploadFlag) {
                boolean isFlag = spcyRsWjmbService.updateById(wjjl);
                if (isFlag) {
                    if (StringUtils.isNotBlank(fcflj)) {
                        localFileUploadUtils.deleteLocalWjmbFileUrl(fcflj);
                    }

                    this.deleteFile(fcflj);
                    /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                    if (!result.isSuccess()){
                        log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                    }*/
                }
            }

        }catch(Exception e){
            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 删除文档
     */
    public void deleteFile(String saveUrl){
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(true);

        String pdfname = GetUuIdUtils.NotReplaceUuId() + Util.getWjHz(saveUrl); // 文件名称

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String ml = "/"+ SpcyConstant.TEMP_WJJL_CHILD_URL +"/" + DateConversionUtils.DateToYear(new Date());

            String realurl = businessConstant.TEMPORARY_UPLOAD_MKDIR_ROOT + ml;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            File delFile = new File(realurl + "/" + pdfname);
            if (delFile.exists()){
                delFile.delete();
            }

        }catch(Exception e){
            log.error("删除文档Exception出错：{}", e.getMessage());
        }
    }


    /**
     * 打开文档
     * @param saveUrl 文件相对路径
     * @param userRight 0 可编辑，1只读
     * @param count 轮询次数 最少为1
     * // @param isSqsx true：申请事项文件；false: 通用文件
     */
    public String openFile(SpcySqsxWjjl wjjl,String fileId,String saveUrl,int count,int userRight){
        return this.openFile(wjjl, fileId, saveUrl, count, userRight, true, false);
    }
    public String openAppFile(SpcySqsxWjjl wjjl,String fileId,String saveUrl,int count,int userRight){
        return this.openFile(wjjl, fileId, saveUrl, count, userRight, true, true);
    }
    public String openFile(SpcySqsxWjjl wjjl,String fileId,String saveUrl,int count,int userRight,boolean isSqsx,boolean isApp){
        if (!isSqsx) {
            saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        }

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+userRight+",";

        if (isApp) {
            params += "\"mobileFlag\": " + isApp + ",";
        }

        params += "\"userId\": \""+ GetCurrentUserUtils.getOfficeUserNameAndOrg() +"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
//                        log.info("打开文档-errorMessage: {}",errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        log.info("打开文档-errorMessage: {}",errorMessage);
                        if (errorMessage.equals("文档不存在。")){
                            if (count == 0){
                                return "";
                            }

                            Result result = null;
                            if (isSqsx) {
                                if (userRight == 0) {
                                    result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                                } else if (userRight == 1) {
                                    result = this.uploadWebOfficeFileByOnlyRead(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                                }
                            }else {
                                result = this.uploadWebOfficeCommonFileByOnlyRead(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                            }
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {

                                if (count == 0){
                                    return "";
                                }
                                count = count - 1;

                                String url2 = this.openFile(wjjl, fileId, saveUrl, count, userRight, isSqsx, isApp);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    public String openQyFile(SpcySqsxQywjcl wjjl,String fileId,String saveUrl,int count,int userRight){
        return openQyFile(wjjl, fileId, saveUrl, count, userRight, false);
    }
    public String openQyFile(SpcySqsxQywjcl wjjl,String fileId,String saveUrl,int count,int userRight,boolean isApp){
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+userRight+",";

        if (isApp) {
            params += "\"mobileFlag\": " + isApp + ",";
        }

        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
//                        log.info("打开文档-errorMessage: {}",errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        log.info("打开文档-errorMessage: {}",errorMessage);
                        if (errorMessage.equals("文档不存在。")){
                            if (count == 0){
                                return "";
                            }

                            Result result = null;

                            result = this.uploadWebOfficeQyFileByOnlyRead(wjjl, wjjl.getFclmc(), wjjl.getFcllj());

                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {
                                if (count == 0){
                                    return "";
                                }
                                count = count - 1;

                                String url2 = this.openQyFile(wjjl, fileId, saveUrl, count, userRight, isApp);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 打开文档 - 质量体系文件 - 在线编辑
     */
    public String openFileByZltxwj(SpcyZltxwjFlow wjjl, String fileId, String saveUrl){
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        log.info("1: {}", saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+0+",";
        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());

        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("打开文档-errorMessage: {}",errorMessage);

                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        if (errorMessage.equals("文档不存在。")){
                            String wjHz = Util.getWjHz(wjjl.getFwjlj()); // 文件类型
                            Result result = this.uploadWebOfficeFileByZltxwj(wjjl, wjjl.getFwjmc() + wjHz, wjjl.getFwjlj());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {
                                String url2 = this.openFileByZltxwj(wjjl, fileId, saveUrl);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 打开文档 - 质量体系文件 - 在线查看
     */
    public String openSeeFileByZltxwj(SpcyZltxwjFlow wjjl, String fileId, String saveUrl){
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
//        log.info("1: {}", saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+1+",";
        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());

        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("打开文档-errorMessage: {}",errorMessage);

                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        if (errorMessage.equals("文档不存在。")){

                            String wjHz = Util.getWjHz(wjjl.getFwjlj()); // 文件类型
                            Result result = this.uploadWebOfficeFileByZltxwj(wjjl, wjjl.getFwjmc() + wjHz, wjjl.getFwjlj());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());

                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {

                                String url2 = this.openSeeFileByZltxwj(wjjl, fileId, saveUrl);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {

                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (IOException e){

            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 打开文档 - 质量体系文件 - 资源库
     */
    public String openFileBaseByZltxwj(SpcyZltxwjBasic wjjl, String fileId, String saveUrl){
        saveUrl = saveUrl.replaceAll("\\\\","/");
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+1+",";
        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("打开文档-errorMessage: {}",errorMessage);

                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        if (errorMessage.equals("文档不存在。")){

                            String wjHz = Util.getWjHz(wjjl.getFwjlj()); // 文件类型
                            Result result = this.uploadWebOfficeFileBaseByZltxwj(wjjl, wjjl.getFwjmc() + wjHz, wjjl.getFwjlj());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());

                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {

                                String url2 = this.openFileBaseByZltxwj(wjjl, fileId, saveUrl);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }

        }catch (IOException e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 打开文档 - 文件模板
     * @param userRight 0：可以编辑;1：只读
     */
    public String openFileByWjmb(SpcyRsWjmb wjjl, String fileId, String saveUrl, int count, int userRight){
        return openFileByWjmb(wjjl, fileId, saveUrl, count, userRight, false);
    }

    /**
     * 打开文档 - 文件模板
     * @param userRight 0：可以编辑;1：只读
     * @param isApp true: app: false: pc
     */
    public String openFileByWjmb(SpcyRsWjmb wjjl, String fileId, String saveUrl, int count, int userRight, boolean isApp){

        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+userRight+",";

        if (isApp) {
            params += "\"mobileFlag\": " + isApp + ",";
        }

        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
//        paramsDecode = HttpUtil.encodeParams(jsonParams.toString(), CharsetUtil.CHARSET_UTF_8);
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);

        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){

                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        log.info("打开文档-errorMessage: {}",errorMessage);
                        if (errorMessage.equals("文档不存在。")){
                            if (count == 0){
                                return "";
                            }
                            Result result = this.uploadWebOfficeFileByWjmb(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {
                                if (count == 0){
                                    return "";
                                }
                                count = count - 1;
                                String url2 = this.openFileByWjmb(wjjl, fileId, saveUrl, count, userRight, isApp);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 打开文档 - 档案文件
     * @param count 递归次数
     */
    public String openSeeFileByDa(SpcyDaWjjl wjjl, String fileId, String saveUrl, int count){
//        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        log.info("1: {}", saveUrl);

        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+1+",";
        params += "\"userId\": \""+GetCurrentUserUtils.getOfficeUserNameAndOrg()+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("打开文档-errorMessage: {}",errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        if (errorMessage.equals("文档不存在。")){
                            if (count == 0){
                                return "";
                            }

                            Result result = this.uploadWebOfficeFileByDa(wjjl, wjjl.getFwjmc(), wjjl.getFwjlj());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {
                                if (count == 0){
                                    return "";
                                }

                                String url2 = this.openSeeFileByDa(wjjl, fileId, saveUrl, count);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 判断文档是否存在
     */
    public boolean isExistFile(String saveUrl){
        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(false);

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response = httpClient.execute(httpget);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    /*long contentLength = res.getContentLength();
                    if (contentLength > 58){
                        return true;
                    }*/
                    String s = EntityUtils.toString(res, "UTF-8");
                    boolean result = false;
                    try {
                        Object obj = JSON.parse(s);
                        result = true;
                    } catch (Exception e) {
                        result = false;
                    }
                    if (!result){
                        return true;
                    }

                    JSONObject jsonObject2 = JSONObject.parseObject(s);
                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("判断文档是否存在-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    log.info("判断文档是否存在-errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        return true;
                    } else {
                        log.error("判断文档是否存在-errorMessage: {}",errorMessage);
                        return false;
                    }

                }
            }else {
                log.error("判断文档是否存在response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("判断文档是否存在response-code: "+response.getStatusLine().getStatusCode());
            }

        }catch(Exception e){
            log.error("判断文档是否存在出错Exception：{}", e.getMessage());
            throw new BusinessException("判断文档是否存在出错Exception: "+e.getMessage());
        }

        return false;
    }

    /**
     * 关闭文档
     */
    public Result closeFile(String fileId){
        String params = "";
        params += "{";
        params += "\"method\": "+3+",";
        params += "\"params\":";
        params += "{";
        params += "\"fileId\": \""+fileId+"\"";
        params += "}";
        params += "}";
       /* params.append("{");
        params.append("\"").append("method").append("\"").append(":").append(3).append(",");
        params.append("\"").append("params").append("\"").append(":");
        params.append("{");
        params.append("\"").append("fileId").append("\"").append(":").append(fileId);
        params.append("}");
        params.append("}");*/
        JSONObject jsonParams = JSON.parseObject(params.toString());

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);

        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("关闭文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("关闭文档-errorMessage: {}",errorMessage);
                        return Result.ok("关闭文档成功");
                    }else {
                        log.error("关闭文档-errorMessage: {}",errorMessage);
                        return Result.error("关闭文档-errorMessage: "+errorMessage);
                    }

                }
            }else {
                if (response.getStatusLine().getStatusCode() == 313){
                    log.error("文档已经关闭response-code: {}", response.getStatusLine().getStatusCode());
                    return Result.ok("文档已经关闭response-code: " + response.getStatusLine().getStatusCode());
                }else {
                    log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                    return Result.error("关闭文档response-code: " + response.getStatusLine().getStatusCode());
                }
            }
        }catch (Exception e){
            log.error("关闭文档出错Exception：{}",e.getMessage());
            return Result.error("关闭文档出错Exception: "+e.getMessage());
        }

        return Result.ok("关闭文档成功");
    }

    /**
     * 判断文档文件是否被打开 (false[未打开]；true[已打开])
     */
    public boolean isOpenFile(String fileId){
        String params = "";
        params += "{";
        params += "\"method\": "+4+",";
        params += "\"params\":";
        params += "{";
        params += "\"fileId\": \""+fileId+"\"";
        params += "}";
        params += "}";
      /*  params.append("\"").append("params").append("\"").append(":");
        params.append("{");
        params.append("\"").append("fileId").append("\"").append(":").append(fileId);
        params.append("}");
        params.append("}");*/
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);
//                    log.info("判断文档文件是否被打开-返回值: {}",jsonObject2);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("判断文档文件是否被打开-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");

                    // result (判断是否已经打开：false[未打开]；true[已打开])
                    boolean result = Boolean.parseBoolean(jsonObject2.getString("result"));
                    log.info("判断文档文件是否被打开-result: {}",result);
                    if (errorCode.equals("0")){
                        log.info("判断文档文件是否被打开-errorMessage: {}",errorMessage);
                        return result;
                    }else {
                        log.error("判断文档文件是否被打开-errorMessage: {}",errorMessage);
                        throw new BusinessException("判断文档文件是否被打开-errorMessage: {}"+errorMessage);
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return true;
    }

    /**
     * 重新编辑pdf
     */
    public SpcySqsxWjjl againEditPdfOnlineFile(SpcySqsxWjjl wjjl){
        if (StringUtils.isBlank(wjjl.getFjdcflj())){
            return null;
        }
        if (StringUtils.isBlank(wjjl.getFcflj())){
            return null;
        }
        if (StringUtils.isBlank(wjjl.getFwjlx()) || !wjjl.getFwjlx().equals(".pdf")){
            return null;
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(wjjl);

        String fjdcflj = wjjl.getFjdcflj(); // 旧的文件路径
        String oldWjlx = Util.getWjHz(fjdcflj); // 旧的文件类型

        if (StringUtils.isNotBlank(wjjl.getFcflj())) {
            localFileUploadUtils.deleteLocalFileUrl(wjjl.getFcflj()); // 删除文件
        }

        wjjl.setFwjlx(oldWjlx);
        wjjl.setFcflj(fjdcflj);
        wjjl.setFwjccmc(Util.getWjmc(fjdcflj));
        wjjl.setFjdcflj("");
        wjjl.setFgzzt(SpcyConstant.WJJL_ZT_GZ_NO);
        wjjl.setFdxzt(SpcyConstant.WJJL_ZT_DX_NO);
        wjjl.setFyxzt(SpcyConstant.WJJL_ZT_YX_NO);
        wjjl.setFwjlx3(SpcyCommonConstant.SQSX_WJJL_TYPE3_ZZZ);
        boolean isFlag = spcySqsxWjjlService.updateById(wjjl);
        if (isFlag) {
            String logNr = "重新编辑PDF文件" + wjjl.getFwjlx1() + "：文件名【" + wjjl.getFwjxsmc() + "】;";
            logNr += LogUtils.BeanModifyMsg(wjjl, oldMap);
            spcyLogService.addLogs("在线编辑", logNr, wjjl.getFpid(), LogConstant.LOGS_SQSX_WJJL, SpcyConstant.LOGS_SYS_TYPE_XG);
        }

        return wjjl;
    }

    /** 质量体系文件流程-重新编辑 */
    public SpcyZltxwjFlow againEditZltxwj(SpcyZltxwjFlow bean){

        String pdfUrl = bean.getFwjlj();
        if (StringUtils.isNotBlank(pdfUrl)){
            localFileUploadUtils.deleteLocalFileUrlByZltxwj(pdfUrl);
        }

        bean.setFwjlj(bean.getFjdwjlj());
        bean.setFwjlx(Util.getWjHz(bean.getFjdwjlj()));
        bean.setFjdwjlj("");
        spcyZltxwjFlowService.updateById(bean);

        return bean;
    }

    /**
     * 初始化HttpPost请求头
     * @param url 请求地址
     * @return
     */
    private HttpPost initHttpPost(String url){
        HttpPost httpRequest = new HttpPost(url);
        // 设置请求头，在Post请求中限制了浏览器后才能访问
        httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        httpRequest.addHeader("Accept", "*/*");
        httpRequest.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpRequest.addHeader("Content-Type", "application/json");
        httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpRequest.addHeader("Connection", "keep-alive");
        return httpRequest;
    }
}
